//
//  XQTabBar.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/18.
//

#import "XQTabBar.h"
#import "XQLoginViewController.h"
#import "XQNavigationController.h"
#import "UIScreen+DDAdd.h"
#import <Masonry/View+MASAdditions.h>

@interface XQTabBar()
@property (nonatomic, strong) XQTabBarItem *selectedItem;
@property (nonatomic, assign) NSInteger selectedIdx;
@end

@implementation XQTabBar


- (void)setTabBarItems:(NSArray<XQTabBarItem *> *)tabBarItems {
    _tabBarItems = tabBarItems;
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self addSubview:self.bgImageView];
    [self addSubview:self.lineView];

    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.top.offset(0);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.and.top.offset(0);
        make.height.equalTo(@(1/[UIScreen screenScale]));
    }];
    
    XQTabBarItem *preItem = nil;
    for (NSInteger i = 0; i < tabBarItems.count; i++) {
        XQTabBarItem *item = tabBarItems[i];
        if (i == 0) {
            item.selected = YES;
            self.selectedItem = item;
            self.selectedIdx = 0;
        }
        
        [self addSubview:item];
        [item mas_makeConstraints:^(MASConstraintMaker *make) {
            if (preItem) {
                make.left.equalTo(preItem.mas_right).offset(0);
                make.width.equalTo(preItem.mas_width);
            } else {
                make.left.offset(0);
            }
            make.top.offset(0);
            make.bottom.offset(-[[UIScreen mainScreen] bottomHeight]);
            if (i == tabBarItems.count - 1) {
                make.right.offset(0);
            }
        }];
        @weakify(self);
        [item setSingleTapHandle:^(XQTabBarItem *item){
            @strongify(self);
            
            if (![XQNetManager isLogin] && i != 0) {
                XQLoginViewController *vc = [XQLoginViewController new];
                [(XQNavigationController *)[XQToolManager appRootViewController] pushViewController:vc animated:YES];
                return;
            }
            
            self.selectedItem.selected = NO;
            item.selected = YES;
            self.selectedItem = item;
            self.selectedIdx = i;
            
            if (self.selectedTabBarItem) {
                self.selectedTabBarItem(i);
            }
        }];
        [item setDoubleTapHandle:^(XQTabBarItem *item){
            @strongify(self);
            if (self.selectedIdx != i) return;
            if (self.doubleTapTabBarItem) {
                self.doubleTapTabBarItem(i);
            }
        }];
        preItem = item;
    }
}


@end
